const { app, BrowserWindow, ipcMain, shell, globalShortcut, Tray, Menu } = require('electron');
const path = require('path');
const fs = require('fs');
const WebSocket = require('ws');
const fetch = require('node-fetch');
const http = require('http');
const url = require('url');

let mainWindow;
let floatingWindow;
let configWindow;
let searchWindow;  // 添加搜索窗口的全局变量
let wsConnection;
let apiPollingInterval;
let httpServer;
let tray;
let config = {
  apiUrl: 'http://localhost:30001/api/push-data',  // 确保使用3000端口
  wsUrl: 'ws://localhost:8081',
  targetUrl: 'http://192.168.14.141:8080/auth?redirect=%2F',  // 修改目标网址
  useWebSocket: false,  // 改为false，默认不启用WebSocket
  useApi: true,         // 保持true，默认启用API接口
  pollingInterval: 5000,
  loginEmail: '1@qq.com', // 新增：自动登录邮箱
  loginPassword: '1'      // 新增：自动登录密码
};

let wsServer = null;

// 启动WebSocket服务器
function startWebSocketServer() {
  if (wsServer) {
    console.log('WebSocket服务器已在运行');
    return;
  }

  try {
    const WebSocket = require('ws');
    const http = require('http');
    
    // 创建HTTP服务器
    const server = http.createServer();
    
    // 创建WebSocket服务器
    wsServer = new WebSocket.Server({ server });
    
    console.log('WebSocket服务器启动中...');
    
    // 连接处理
    wsServer.on('connection', (ws, req) => {
      console.log('新的WebSocket连接已建立');
      console.log('客户端地址:', req.socket.remoteAddress);
      console.log('客户端端口:', req.socket.remotePort);
      
      // 发送欢迎消息
      ws.send(JSON.stringify({
        type: 'welcome',
        message: 'WebSocket服务器连接成功',
        timestamp: new Date().toISOString()
      }));
      
      // 消息处理
      ws.on('message', (message) => {
        try {
          const data = message.toString();
          console.log('收到WebSocket消息:', data);
          
          // 先提取字符串内容
          let displayStr = message;
          try {
            const jsonData = JSON.parse(message);
            if (typeof jsonData === 'string') displayStr = jsonData;
            else if (jsonData.message) displayStr = jsonData.message;
            else if (jsonData.keyword) displayStr = jsonData.keyword;
            else if (jsonData.data) displayStr = jsonData.data;
            else if (jsonData.q) displayStr = jsonData.q;
            else displayStr = JSON.stringify(jsonData);
          } catch {

          }
          // 回显到悬浮窗最新数据框
          if (floatingWindow) {
            floatingWindow.webContents.send('data-received', { data: displayStr, timestamp: new Date().toLocaleString() });
          }

          handleReceivedData(data);
        } catch (error) {
          console.error('处理WebSocket消息失败:', error);
        }
      });
      
      // 连接关闭
      ws.on('close', () => {
        console.log('WebSocket连接已关闭');
      });
      
      // 连接错误
      ws.on('error', (error) => {
        console.error('WebSocket连接错误:', error);
      });
    });
    
    // 启动服务器
    const PORT = 8081;
    server.listen(PORT, '127.0.0.1', () => {
      console.log(`✅ WebSocket服务器已启动`);
      console.log(`📍 地址: ws://127.0.0.1:${PORT}`);
      console.log(`📍 地址: ws://localhost:${PORT}`);
    });
    
    // 错误处理
    server.on('error', (error) => {
      if (error.code === 'EADDRINUSE') {
        console.log(`⚠️  端口 ${PORT} 已被占用，WebSocket服务器启动失败`);
        wsServer = null;
      } else {
        console.error('WebSocket服务器错误:', error);
        wsServer = null;
      }
    });
    
  } catch (error) {
    console.error('启动WebSocket服务器失败:', error.message);
    wsServer = null;
  }
}

// 停止WebSocket服务器
function stopWebSocketServer() {
  if (wsServer) {
    wsServer.close(() => {
      console.log('WebSocket服务器已关闭');
      wsServer = null;
    });
  }
}

// 配置文件路径
const configPath = path.join(app.getPath('userData'), 'config.json');

// 创建系统托盘
function createTray() {
  try {
    // 使用指定的系统托盘图标
    const iconPath = path.join(__dirname, 'assets', 'sysIcon.ico');
    
    let icon;
    if (fs.existsSync(iconPath)) {
      icon = iconPath;
      console.log('使用系统托盘图标:', iconPath);
    } else {
      icon = undefined;
      console.log('系统托盘图标文件不存在，使用默认图标');
    }
    
    // 创建托盘
    tray = new Tray(icon);
    tray.setToolTip('悬浮桌面应用');
    
    console.log('系统托盘创建成功');
    
    // 创建托盘菜单
    const contextMenu = Menu.buildFromTemplate([
      {
        label: '显示悬浮窗口',
        click: () => {
          console.log('点击显示悬浮窗口');
          if (floatingWindow) {
            floatingWindow.show();
            floatingWindow.focus();
          }
        }
      },
      {
        label: '配置设置',
        click: () => {
          console.log('点击配置设置');
          createConfigWindow();
        }
      },
      { type: 'separator' },
      {
        label: '开始监听',
        click: () => {
          console.log('点击开始监听');
          startListening();
        }
      },
      {
        label: '停止监听',
        click: () => {
          console.log('点击停止监听');
          stopListening();
        }
      },
      { type: 'separator' },
      {
        label: '退出应用',
        click: () => {
          console.log('用户点击退出应用');
          
          // 设置退出标志
          app.isQuiting = true;
          
          // 停止所有监听
          stopListening();
          
          // 关闭所有窗口
          if (floatingWindow && !floatingWindow.isDestroyed()) {
            floatingWindow.close();
          }
          if (configWindow && !configWindow.isDestroyed()) {
            configWindow.close();
          }
          if (searchWindow && !searchWindow.isDestroyed()) {
            searchWindow.close();
          }
          if (mainWindow && !mainWindow.isDestroyed()) {
            mainWindow.close();
          }
          
          // 销毁托盘
          if (tray) {
            tray.destroy();
            tray = null;
          }
          
          // 强制退出应用
          setTimeout(() => {
            app.exit(0);
          }, 100);
        }
      }
    ]);
    
    tray.setContextMenu(contextMenu);
    
    // 双击托盘图标显示悬浮窗口
    tray.on('double-click', () => {
      console.log('双击托盘图标');
      if (floatingWindow) {
        if (floatingWindow.isVisible()) {
          floatingWindow.focus();
        } else {
          floatingWindow.show();
          floatingWindow.focus();
        }
      }
    });
    
    // 单击托盘图标也显示悬浮窗口
    tray.on('click', () => {
      console.log('单击托盘图标');
      if (floatingWindow) {
        if (floatingWindow.isVisible()) {
          floatingWindow.focus();
        } else {
          floatingWindow.show();
          floatingWindow.focus();
        }
      }
    });
    
  } catch (error) {
    console.error('创建系统托盘失败:', error);
    // 如果托盘创建失败，继续运行应用但不显示托盘
  }
}

// 更新托盘菜单状态
function updateTrayMenu() {
  if (!tray) return;
  
  const isListening = (wsConnection && config.useWebSocket) || (httpServer && config.useApi);
  
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '显示悬浮窗口',
      click: () => {
        if (floatingWindow) {
          floatingWindow.show();
          floatingWindow.focus();
        }
      }
    },
    {
      label: '配置设置',
      click: () => {
        createConfigWindow();
      }
    },
    { type: 'separator' },
    {
      label: isListening ? '停止监听' : '开始监听',
      click: () => {
        if (isListening) {
          stopListening();
        } else {
          startListening();
        }
      }
    },
    { type: 'separator' },
    {
      label: '退出应用',
      click: () => {
        app.quit();
      }
    }
  ]);
  
  tray.setContextMenu(contextMenu);
}

// 加载配置
function loadConfig() {
  try {
    if (fs.existsSync(configPath)) {
      const data = fs.readFileSync(configPath, 'utf8');
      config = { ...config, ...JSON.parse(data) };
    }
  } catch (error) {
    console.error('加载配置失败:', error);
  }
}

// 保存配置
function saveConfig() {
  try {
    fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
    // 主动推送配置到悬浮窗口
    if (floatingWindow) {
      floatingWindow.webContents.send('config-data', config);
    }
  } catch (error) {
    console.error('保存配置失败:', error);
  }
}

// 创建主窗口
function createMainWindow() {
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    },
    show: false
  });

  mainWindow.loadFile('index.html');

  mainWindow.on('closed', () => {
    mainWindow = null;
  });
}

// 悬浮窗口创建后推送一次配置
function createFloatingWindow() {
  floatingWindow = new BrowserWindow({
    width: 320,
    height: 520,
    frame: false,
    alwaysOnTop: true,
    resizable: false,
    skipTaskbar: true,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    }
  });

  floatingWindow.loadFile('floating.html');

  // 设置窗口位置（屏幕右下角）
  const { screen } = require('electron');
  const primaryDisplay = screen.getPrimaryDisplay();
  const { width, height } = primaryDisplay.workAreaSize;
  floatingWindow.setPosition(width - 340, height - 540);

  floatingWindow.on('minimize', () => {
    floatingWindow.hide();
    if (tray) {
      tray.setToolTip('悬浮桌面应用 (已最小化)');
    }
  });

  floatingWindow.on('close', (event) => {
    if (!app.isQuiting) {
      event.preventDefault();
      floatingWindow.hide();
      if (tray) {
        tray.setToolTip('悬浮桌面应用 (已隐藏)');
      }
    }
  });

  floatingWindow.on('closed', () => {
    floatingWindow = null;
  });

  // 悬浮窗口加载完成后推送一次配置
  floatingWindow.webContents.on('did-finish-load', () => {
    floatingWindow.webContents.send('config-data', config);
  });
}

// 创建配置窗口
function createConfigWindow() {
  if (configWindow) {
    configWindow.focus();
    return;
  }

  // 先计算屏幕中央位置
  const { screen } = require('electron');
  const primaryDisplay = screen.getPrimaryDisplay();
  const { width: screenWidth, height: screenHeight } = primaryDisplay.workAreaSize;

  // 计算窗口居中位置
  const windowWidth = 480;
  const windowHeight = 1000; // 高度增加350px
  const x = Math.round((screenWidth - windowWidth) / 2);
  const y = Math.round((screenHeight - windowHeight) / 2);

  configWindow = new BrowserWindow({
    width: windowWidth,
    height: windowHeight,
    x: x,
    y: y,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false
    },
    parent: floatingWindow,
    modal: true,
    center: false,
    resizable: false,
    minimizable: false,
    maximizable: false,
    show: false
  });

  configWindow.loadFile('config.html');

  configWindow.once('ready-to-show', () => {
    configWindow.show();
    console.log(`配置窗口已居中显示，位置: (${x}, ${y})`);
  });

  configWindow.on('closed', () => {
    configWindow = null;
  });
}

// 启动WebSocket连接
function startWebSocket() {
  if (wsConnection) {
    wsConnection.close();
  }

  try {
    // 确保使用IPv4地址
    let wsUrl = config.wsUrl;
    if (wsUrl.includes('localhost')) {
      wsUrl = wsUrl.replace('localhost', '127.0.0.1');
    }
    
    console.log('尝试连接WebSocket:', wsUrl);
    wsConnection = new WebSocket(wsUrl);
    
    // 设置连接超时
    const connectionTimeout = setTimeout(() => {
      if (wsConnection.readyState === WebSocket.CONNECTING) {
        console.log('WebSocket连接超时');
        wsConnection.close();
      }
    }, 5000);
    
    wsConnection.on('open', () => {
      clearTimeout(connectionTimeout);
      console.log('WebSocket连接已建立');
      if (floatingWindow) {
        floatingWindow.webContents.send('ws-status', { connected: true });
      }
      updateTrayMenu();
    });

    wsConnection.on('message', (data) => {
      const msg = data.toString();
      // 先提取字符串内容
      let displayStr = msg;
      try {
        const jsonData = JSON.parse(msg);
        if (typeof jsonData === 'string') displayStr = jsonData;
        else if (jsonData.message) displayStr = jsonData.message;
        else if (jsonData.keyword) displayStr = jsonData.keyword;
        else if (jsonData.data) displayStr = jsonData.data;
        else if (jsonData.q) displayStr = jsonData.q;
        else displayStr = JSON.stringify(jsonData);
      } catch {}
      // 回显到悬浮窗最新数据框
      if (floatingWindow) {
        floatingWindow.webContents.send('data-received', { data: displayStr, timestamp: new Date().toLocaleString() });
      }
      // 再调用handleReceivedData
      handleReceivedData(msg);
    });

    wsConnection.on('close', () => {
      clearTimeout(connectionTimeout);
      console.log('WebSocket连接已关闭');
      if (floatingWindow) {
        floatingWindow.webContents.send('ws-status', { connected: false });
      }
      updateTrayMenu();
    });

    wsConnection.on('error', (error) => {
      clearTimeout(connectionTimeout);
      console.log('WebSocket连接失败（服务器可能未运行）:', error.message);
      // 不显示错误状态，只显示为未连接
      if (floatingWindow) {
        floatingWindow.webContents.send('ws-status', { connected: false });
      }
      updateTrayMenu();
    });
  } catch (error) {
    console.log('启动WebSocket失败:', error.message);
    // 不显示错误状态，只显示为未连接
    if (floatingWindow) {
      floatingWindow.webContents.send('ws-status', { connected: false });
    }
  }
}

// 启动HTTP服务器
function startHttpServer() {
  if (httpServer) {
    httpServer.close();
  }

  // 从API URL中提取端口号
  const apiUrl = new URL(config.apiUrl);
  const port = apiUrl.port || 3000;

  httpServer = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true);
    const pathname = parsedUrl.pathname;

    if (pathname === '/api/push-data') {
      if (req.method === 'POST') {
        // 处理POST请求
        let body = '';
        req.on('data', (chunk) => {
          body += chunk;
        });
        req.on('end', () => {
          try {
            // 设置正确的编码处理
            req.setEncoding('utf8');
            
            // 尝试解析JSON，如果失败则直接使用字符串
            let data;
            try {
              data = JSON.parse(body);
              data = typeof data === 'string' ? data : JSON.stringify(data);
            } catch {
              data = body;
            }
            
            console.log('收到HTTP POST数据:', data);
            console.log('原始body数据:', body);
            handleReceivedData(data);
            
            res.writeHead(200, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ 
              success: true, 
              message: 'Data received successfully',
              data: data 
            }));
          } catch (error) {
            console.error('处理HTTP POST数据失败:', error);
            res.writeHead(500, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ error: 'Internal server error' }));
          }
        });
      } else if (req.method === 'GET') {
        // 处理GET请求
        try {
          // 从查询参数中获取数据
          const queryData = parsedUrl.query;
          let data = '';
          
          // 支持多种参数名
          if (queryData.data) {
            data = queryData.data;
          } else if (queryData.q) {
            data = queryData.q;
          } else if (queryData.message) {
            data = queryData.message;
          } else if (queryData.keyword) {
            data = queryData.keyword;
          } else {
            // 如果没有指定参数名，使用第一个参数的值
            const firstKey = Object.keys(queryData)[0];
            if (firstKey) {
              data = queryData[firstKey];
            }
          }
          
          if (data) {
            console.log('收到HTTP GET数据:', data);
            console.log('查询参数:', queryData);
            handleReceivedData(data);
            
            res.writeHead(200, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ 
              success: true, 
              message: 'Data received successfully',
              data: data,
              method: 'GET'
            }));
          } else {
            // 如果没有数据参数，返回API信息
            res.writeHead(200, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ 
              message: 'API server is running',
              endpoint: '/api/push-data',
              methods: ['GET', 'POST'],
              examples: {
                get: 'http://localhost:30001/api/push-data?data=搜索关键词',
                post: 'POST http://localhost:30001/api/push-data with JSON body'
              }
            }));
          }
        } catch (error) {
          console.error('处理HTTP GET数据失败:', error);
          res.writeHead(500, { 'Content-Type': 'application/json' });
          res.end(JSON.stringify({ error: 'Internal server error' }));
        }
      } else {
        // 不支持的HTTP方法
        res.writeHead(405, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ 
          error: 'Method not allowed',
          allowedMethods: ['GET', 'POST']
        }));
      }
    } else {
      res.writeHead(404, { 'Content-Type': 'text/plain' });
      res.end('Not Found');
    }
  });

  // 尝试启动服务器，如果端口被占用则尝试其他端口
  function tryStartServer(portToTry) {
    httpServer.listen(portToTry, () => {
      console.log(`HTTP服务器已启动在端口 ${portToTry}`);
      console.log(`API端点: http://localhost:${portToTry}/api/push-data`);
      
      // 更新配置中的API URL
      const newApiUrl = `http://localhost:${portToTry}/api/push-data`;
      if (config.apiUrl !== newApiUrl) {
        config.apiUrl = newApiUrl;
        saveConfig();
        console.log(`API URL已更新为: ${newApiUrl}`);
      }
      
      // 通知悬浮窗口HTTP服务器已启动
      if (floatingWindow) {
        floatingWindow.webContents.send('api-status', { active: true });
      }
      updateTrayMenu();
    });

    httpServer.on('error', (error) => {
      if (error.code === 'EADDRINUSE') {
        console.log(`端口 ${portToTry} 被占用，尝试端口 ${portToTry + 1}`);
        if (portToTry < 3005) { // 减少尝试范围，最多尝试到3004
          tryStartServer(portToTry + 1);
        } else {
          console.error('无法找到可用端口');
          if (floatingWindow) {
            floatingWindow.webContents.send('api-status', { active: false, error: '无法找到可用端口' });
          }
        }
      } else {
        console.error('HTTP服务器错误:', error);
        if (floatingWindow) {
          floatingWindow.webContents.send('api-status', { active: false, error: error.message });
        }
      }
    });
  }

  tryStartServer(port);
}

// 处理接收到的数据
function handleReceivedData(data) {
  let searchKeyword = data;
  try { searchKeyword = decodeURIComponent(data); } catch {}
  try {
    const jsonData = JSON.parse(searchKeyword);
    if (typeof jsonData === 'string') searchKeyword = jsonData;
    else if (jsonData.message) searchKeyword = jsonData.message;
    else if (jsonData.keyword) searchKeyword = jsonData.keyword;
    else if (jsonData.data) searchKeyword = jsonData.data;
    else if (jsonData.q) searchKeyword = jsonData.q; // 新增对q字段的支持
    else searchKeyword = JSON.stringify(jsonData);
  } catch {}

  const targetUrl = config.targetUrl;

  // 检查搜索窗口是否存在且未关闭
  if (searchWindow && !searchWindow.isDestroyed()) {
    // 如果窗口存在，直接加载目标URL
    console.log('窗口已存在，更新目标网址');
    searchWindow.loadURL(targetUrl);
    searchWindow.focus(); // 将窗口置于前台
  } else {
    // 如果窗口不存在，创建新窗口
    console.log('创建新的窗口');
    searchWindow = new BrowserWindow({
      width: 1200,
      height: 800,
      webPreferences: {
        nodeIntegration: false,
        contextIsolation: false,
        webSecurity: false,
        allowRunningInsecureContent: true
      }
    });
    searchWindow.loadURL(targetUrl);
    searchWindow.on('closed', () => { searchWindow = null; });
  }

  // 只监听一次 did-finish-load，自动移除监听
  const onceLoginHandler = () => {
    console.log('页面加载完成，开始执行登录和输入操作');
    setTimeout(() => {
      performLoginAndInput(searchWindow, searchKeyword);
    }, 3000);
    searchWindow.webContents.removeListener('did-finish-load', onceLoginHandler);
  };
  searchWindow.webContents.on('did-finish-load', onceLoginHandler);

  // 不再监听 did-navigate、did-navigate-in-page

  // 通知悬浮窗口
  if (floatingWindow) {
    console.log('正在向悬浮窗口发送数据:', { data: searchKeyword, timestamp: new Date().toLocaleString() });
    
    // 确保悬浮窗口完全加载后再发送数据
    if (floatingWindow.webContents.isLoading()) {
      console.log('悬浮窗口正在加载，等待加载完成...');
      floatingWindow.webContents.once('did-finish-load', () => {
        console.log('悬浮窗口加载完成，发送数据');
        floatingWindow.webContents.send('data-received', { data: searchKeyword, timestamp: new Date().toLocaleString() });
        console.log('数据已发送到悬浮窗口');
      });
    } else {
      floatingWindow.webContents.send('data-received', { data: searchKeyword, timestamp: new Date().toLocaleString() });
      console.log('数据已发送到悬浮窗口');
    }
  } else {
    console.log('悬浮窗口不存在，无法发送数据');
  }
  
  // 显示托盘通知
  if (tray) {
    try {
      tray.displayBalloon({
        title: '悬浮应用',
        content: `收到新数据: ${searchKeyword.substring(0, 50)}${searchKeyword.length > 50 ? '...' : ''}`
      });
      console.log('托盘通知显示成功');
    } catch (error) {
      console.error('显示托盘通知失败:', error);
    }
  }
}

// 执行登录和输入操作
function performLoginAndInput(window, inputText) {
  // 通过preload注入config，或直接序列化config字段
  const loginEmail = config.loginEmail || '1@qq.com';
  const loginPassword = config.loginPassword || '1';
  window.webContents.executeJavaScript(`
    (function autoLoginAndInput() {
      if (window._autoLoginTimer) {
        clearTimeout(window._autoLoginTimer);
        window._autoLoginTimer = null;
      }
      if (window._autoLoginClicked && window._autoLoginInputDone) return;
      let tryCount = 0;
      function simulateInput(el, value) {
        el.focus();
        el.value = '';
        for (let i = 0; i < value.length; i++) {
          el.value += value[i];
          el.dispatchEvent(new Event('input', { bubbles: true }));
          el.dispatchEvent(new KeyboardEvent('keydown', { key: value[i], bubbles: true }));
        }
        el.dispatchEvent(new Event('input', { bubbles: true }));
        el.dispatchEvent(new Event('change', { bubbles: true }));
        el.dispatchEvent(new Event('blur', { bubbles: true }));
      }
      function tryLoginAndInput() {
        if (window._autoLoginClicked && window._autoLoginInputDone) return;
        tryCount++;
        let emailInput = document.querySelector('input[type="email"], input[placeholder*="邮箱"], input[placeholder*="email"], input[name="email"]');
        let passwordInput = document.querySelector('input[type="password"], input[placeholder*="密码"], input[name="password"]');
        let loginButton = document.querySelector('button[type="submit"]');
        if (!loginButton) {
          loginButton = Array.from(document.querySelectorAll('button')).find(
            el => /登录|login/i.test(el.innerText) && el.offsetParent !== null
          );
        }
        if (!window._autoLoginClicked && emailInput && passwordInput && loginButton) {
          console.log('[AUTOLOGIN] 找到邮箱/密码/登录按钮，自动填充...');
          simulateInput(emailInput, '${loginEmail.replace(/'/g, "\\'")}');
          setTimeout(() => {
            simulateInput(passwordInput, '${loginPassword.replace(/'/g, "\\'")}');
            setTimeout(() => {
              if (!loginButton.disabled) {
                loginButton.focus();
                loginButton.click();
                window._autoLoginClicked = true;
                if (window._autoLoginTimer) {
                  clearTimeout(window._autoLoginTimer);
                  window._autoLoginTimer = null;
                }
                console.log('[AUTOLOGIN] 已点击登录按钮，只会点一次');
                setTimeout(tryLoginAndInput, 1200);
                return;
              } else {
                console.log('[AUTOLOGIN] 登录按钮被禁用，等待激活...');
              }
            }, 400);
          }, 400);
          return;
        }
        const selectors = [
          'textarea[placeholder*="帮您"]','textarea[placeholder*="什么"]','textarea','input[type="text"]','[contenteditable="true"]','.chat-input','[class*="input"]','[class*="textarea"]'
        ];
        let chatInput = null;
        for (let selector of selectors) {
          const el = document.querySelector(selector);
          if (el && el.offsetParent !== null) { chatInput = el; break; }
        }
        if (chatInput) {
          chatInput.focus();
          if (chatInput.tagName === 'TEXTAREA' || chatInput.tagName === 'INPUT') {
            chatInput.value = '';
            chatInput.value = '${inputText.replace(/'/g, "\\'")}';
          } else if (chatInput.contentEditable === 'true') {
            chatInput.textContent = '';
            chatInput.textContent = '${inputText.replace(/'/g, "\\'")}';
          }
          chatInput.dispatchEvent(new Event('input', { bubbles: true }));
          chatInput.dispatchEvent(new Event('change', { bubbles: true }));
          chatInput.dispatchEvent(new Event('blur', { bubbles: true }));
          window._autoLoginInputDone = true;
          console.log('[AUTOLOGIN] 已将字符串填入输入框，不自动发送');
          return;
        }
        if (tryCount < 40) {
          console.log('[AUTOLOGIN] 未找到目标元素，重试第' + tryCount + '次');
          window._autoLoginTimer = setTimeout(tryLoginAndInput, 1500);
        } else {
          console.log('[AUTOLOGIN] 超过最大重试次数，放弃');
          window._autoLoginTimer = null;
        }
      }
      tryLoginAndInput();
    })();
  `);
}

// 启动监听
function startListening() {
  // 同时启动WebSocket和API接口
  if (config.useWebSocket) {
    startWebSocket();
  }
  if (config.useApi) {
    startHttpServer();
  }
}

// 停止监听
function stopListening() {
  if (wsConnection) {
    wsConnection.close();
    wsConnection = null;
  }
  if (apiPollingInterval) {
    clearInterval(apiPollingInterval);
    apiPollingInterval = null;
  }
  if (httpServer) {
    httpServer.close();
    httpServer = null;
  }
  
  // 通知悬浮窗口状态更新
  if (floatingWindow) {
    floatingWindow.webContents.send('ws-status', { connected: false });
    floatingWindow.webContents.send('api-status', { active: false });
  }
  updateTrayMenu();
}

// IPC事件处理
ipcMain.on('show-config', () => {
  createConfigWindow();
});

ipcMain.on('get-config', (event) => {
  event.reply('config-data', config);
});

ipcMain.on('floating-window-ready', () => {
  console.log('悬浮窗口已准备就绪');
  // 可以在这里发送任何待处理的数据
});

ipcMain.on('save-config', (event, newConfig) => {
  config = { ...config, ...newConfig };
  saveConfig();
  startListening(); // 重新启动监听
  event.reply('config-saved');
});

ipcMain.on('start-listening', () => {
  startListening();
});

ipcMain.on('stop-listening', () => {
  stopListening();
});

ipcMain.on('minimize-floating', () => {
  if (floatingWindow) {
    floatingWindow.minimize();
  }
});

ipcMain.on('close-floating', () => {
  if (floatingWindow) {
    floatingWindow.hide();
  }
});

// 应用事件
app.whenReady().then(() => {
  console.log('应用启动中...');
  loadConfig();
  console.log('配置加载完成');
  
  createTray();
  console.log('托盘创建完成');
  
  createFloatingWindow();
  console.log('悬浮窗口创建完成');
  
  // 注册全局快捷键
  globalShortcut.register('Ctrl+Shift+F', () => {
    console.log('快捷键触发');
    if (floatingWindow) {
      if (floatingWindow.isVisible()) {
        floatingWindow.hide();
      } else {
        floatingWindow.show();
        floatingWindow.focus();
      }
    }
  });
  
  // 自动启动WebSocket服务器
  console.log('自动启动WebSocket服务器...');
  startWebSocketServer();
  
  // 自动启动WebSocket连接
  console.log('自动启动WebSocket连接...');
  startWebSocket();
  
  // 自动开始监听
  console.log('自动开始监听...');
  startListening();
  
  console.log('应用启动完成，托盘状态:', tray ? '已创建' : '创建失败');
});

app.on('window-all-closed', () => {
  // 只有在非退出状态下才阻止应用退出
  if (!app.isQuiting && process.platform !== 'darwin') {
    // 不退出应用，保持托盘运行
    return;
  }
});

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createFloatingWindow();
  }
});

app.on('will-quit', () => {
  console.log('应用即将退出...');
  app.isQuiting = true;
  globalShortcut.unregisterAll();
  stopListening();
  stopWebSocketServer();
  
  // 关闭所有窗口
  if (searchWindow && !searchWindow.isDestroyed()) {
    searchWindow.close();
  }
  if (floatingWindow && !floatingWindow.isDestroyed()) {
    floatingWindow.close();
  }
  if (configWindow && !configWindow.isDestroyed()) {
    configWindow.close();
  }
  if (mainWindow && !mainWindow.isDestroyed()) {
    mainWindow.close();
  }
  
  // 销毁托盘
  if (tray) {
    tray.destroy();
    tray = null;
  }
});

// 添加before-quit事件处理
app.on('before-quit', () => {
  console.log('应用准备退出...');
  app.isQuiting = true;
}); 